package com.qf.springcloud.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.http.HttpStatus;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

@Component
public class AuthenticationFilter extends ZuulFilter {

    /**
     * 设置当前过滤器类型
     * @return
     */
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    /**
     * 设置多个同类型过滤器的执行顺序
     * @return
     */
    @Override
    public int filterOrder() {
        return FilterConstants.SEND_FORWARD_FILTER_ORDER - 100;
    }

    /**
     * 过滤器开关
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 业务逻辑
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        //1. 获取当前请求的上下文
        RequestContext requestContext = RequestContext.getCurrentContext();

        //2. 获取Request
        HttpServletRequest request = requestContext.getRequest();

        //3. 接收token，校验
        String token = request.getParameter("token");
        if(StringUtils.isEmpty(token) || !"123".equals(token)){
            // 没有权限，返回401
            // 到这停！！
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(HttpStatus.SC_UNAUTHORIZED);
        }
        return null;
    }
}
